<html>

<head>
  <script type="text/javascript" src="../../../../blockly_uncompressed.js"></script>
  <script type="text/javascript" src="https://unpkg.com/pxt-blockly@2.1.12/blocks_compressed.js"></script>
  <script type="text/javascript" src="https://unpkg.com/pxt-blockly@2.1.12/msg/messages.js"></script>
  <script type="text/javascript" src="../../../playgrounds/screenshot.js"></script>

  <style id="blocklycss">
    .blocklyText,
    .blocklyHtmlInput {
      font-family: "Helvetica Neue", "Segoe UI", Helvetica, sans-serif;
      font-weight: bold;
      font-size: 12pt;
    }

    .blocklyNonEditableText>text,
    .blocklyEditableText>text,
    .blocklyNonEditableText>g>text,
    .blocklyEditableText>g>text {
      fill: #575E75;
    }

    .blocklyHtmlInput {
      color: #575E75;
    }
  </style>
</head>

<body>
  <div id="blocklyDiv"></div>
  <script>
    goog.require('Blockly.blockRendering.Debug');
    goog.require('Blockly.zelos.Renderer');
    // Blockly.blockRendering.startDebugger();

    // This stub is a workaround in order to load pxt-blockly blocks, as they
    // rely on a setOutputShape method on the block.
    Blockly.BlockSvg.prototype.setOutputShape = function() { };

    var blocklyDiv = document.getElementById('blocklyDiv');
    var workspace;
    window.addEventListener('message', function (msg) {
      var data = msg.data;
      if (data.type !== 'post') {
        return;
      }
      var xml = data.xml;
      try {
        if (workspace) {
          workspace.dispose();
          blocklyDiv.innerHTML = '';
          window.parent.focus();
        }
      } catch { }

      workspace = Blockly.inject(blocklyDiv, {
        renderer: 'zelos',
        move: {
          scrollbars: true,
          drag: true,
          wheel: false,
        },
        zoom: {
          wheel: true,
          startScale: 2,
        }
      });
      var constants = workspace.getRenderer().getConstants();
      constants.FIELD_TEXT_FONTSIZE = 12;
      constants.FIELD_TEXT_FONTWEIGHT = 'bold';
      constants.FIELD_TEXT_FONTFAMILY = 'Helvetica Neue';

      Blockly.Xml.domToWorkspace(Blockly.Xml.textToDom(xml), workspace);

      function postChange() {
        try {
          var topBlock = workspace.getTopBlocks()[0];
          workspaceToSvg_(workspace, function (datauri) {
            window.parent.postMessage({
              type: 'svg',
              from: 'zelos',
              text: datauri
            }, '*');
          }, document.getElementById('blocklycss').innerText);
        } catch (err) {
          console.error(err);
        }
      }

      workspace.addChangeListener(function(e) {
        if (e.type != 'ui') {
          postChange();
        }
      });

      postChange();
    });
  </script>
</body>

</html>